<template>
  <div class="tableContainer">
    <div class="cardTop">
      <el-card>
        <div class="searchCondition">筛选条件</div>
        <el-form :inline="true" :model="formInline" style="margin: 30px 0 0 0">
          <el-form-item label="追溯码">
            <div class="traceableCodeInput">
              <el-input autofocus v-model="formInline.traceableCode"
                        placeholder="请输入追溯码" />
            </div>
          </el-form-item>
          <el-form-item label="采购商">
            <el-input style="margin: 0 10px" v-model="formInline.hospital" placeholder="请输入采购商" />
          </el-form-item>

          <el-form-item label="出库时间" clearable>
            <el-date-picker type="daterange" format="YYYY/MM/DD" value-format="YYYY/MM/DD"
                            range-separator="至" start-placeholder="开始日期" v-model="formInline.createTime"
                            end-placeholder="结束日期" @change="onTimeChange" clearable></el-date-picker>
          </el-form-item>
          <el-form-item>

          </el-form-item>
        </el-form>
        <el-button type="primary" @click="onSearchCode">筛选</el-button>
        <el-button color="#E6F1FC" @click="onRestBtn">重置</el-button>
      </el-card>
    </div>
    <div class="outerTable">

      <div>
        <el-button type="primary" @click="onOutbound">新建出库</el-button>
        <el-button color="#E6F1FC" @click="onExportError">导出</el-button>
      </div>

      <el-table ref="tableRef" :height="tableHeight" :data="formInline.traceableData">
        <el-table-column type="index" label="序号" width="120" />
        <el-table-column prop="hospital" label="采购商" width="300" />
        <el-table-column prop="purchaseAddress" label="采购地址" />
        <el-table-column prop="invoiceNumber" label="出库单" width="220" />
        <el-table-column prop="saveTime" label="出库时间" width="180">
          <template #default="{row}">
            <span>{{ formatDateTable(row.saveTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="purchasesItemList" label="追溯码" width="520">
          <template #default="{row}">
            <div v-if="row.purchasesItemList.length >=  1" class="tagCodeStyle">
              <el-tooltip effect="dark" placement="top-start"
                          :disabled="row.purchasesItemList[0].traceableCode.length < 60">
                <template #content>
                  <div style="max-width: 700px">
                    <div>
                      {{ row.purchasesItemList[0].traceableCode }}
                    </div>
                  </div>
                </template>
                <el-tag class="purchasesTag">
                  {{ row.purchasesItemList[0].traceableCode }}
                </el-tag>
              </el-tooltip>

              <el-tooltip placement="left" effect="light" :disabled="row.purchasesItemList.length <= 1">
                <template #content>
                  <div class="tooltipStyle">
                    <el-scrollbar height="500px">
                      <span class="tooltipTitle">追溯码详情</span>
                      <div class="tooltipContent" v-for="(item,index) in row.purchasesItemList">
                        <div :style="{ backgroundColor: index % 2 === 0 ? '#dff0d8' : '#fcf8e3'}">
                          {{ item.traceableCode }}
                        </div>
                      </div>
                    </el-scrollbar>
                  </div>
                </template>
                <img src="../../assets/images/xia.png" v-show="row.purchasesItemList.length >  1">
              </el-tooltip>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="saveTime" label="操作" width="150" align="center">
          <template #default="{row}">
            <el-link style="color: #0486FE" :underline="false" @click="onDeleteCode(row)">
              删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <div class="cardFoot">
        <el-pagination
          style="margin: 20px 0 0 0" :page-size="formInline.pageSize"
          :page-sizes="[10, 20, 50]"
          layout="prev, pager, next,total, sizes"
          :total="formInline.count"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>

  <el-dialog title="新建出库单" v-model="dialogFormVisible" width="642px" :close-on-click-modal="false">
    <el-form :model="saveFormCode" label-position="left" style="margin: 10px auto;width: 580px">
      <el-form-item label="采购商" :label-width="formLabelWidth">
        <el-input placeholder="请输入采购商" v-model="saveFormCode.hospital" autocomplete="off" />
      </el-form-item>
      <el-form-item label="采购商地址" :label-width="formLabelWidth">
        <el-input placeholder="请输入采购商地址" v-model="saveFormCode.purchaseAddress" autocomplete="off" />
      </el-form-item>
      <el-form-item label="出库单号" :label-width="formLabelWidth">
        <el-input placeholder="请输入出库单号" v-model="saveFormCode.invoiceNumber" autocomplete="off" />
      </el-form-item>
      <el-form-item label="追溯码" :label-width="formLabelWidth">
        <div class="tagStyle" v-show="saveFormCode.purchasesItemList.length >= 1">
          <el-scrollbar height="200px">
            <el-tag v-for="tag in saveFormCode.purchasesItemList" closable
                    @close="onHandleClose(tag)" style="margin: 5px">
              {{ tag.traceableCode }}
            </el-tag>
          </el-scrollbar>
        </div>
        <el-input placeholder="请输入追溯码" ref="dialogInputRef" v-model="saveFormCode.saveCode" autocomplete="off"
                  style="margin:5px 0" />
        <div v-show="ruleCode === 1 || ruleCode === 2" style="color: #f22727;">
          {{ ruleCode === 1 ? '追溯码不正确' : '追溯码重复' }}
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="dialogFormVisible = false">取消</el-button>
      <el-button @click="onSaveCode">保存</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { onMounted, reactive, ref, watch } from 'vue'
import api from '@/api/index.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { calcTableHeight } from '@/utils/table.js'

const dialogFormVisible = ref(false) // 控制弹窗显示
const formLabelWidth = '100px' // 表单项的label宽度
const dialogInputRef = ref()
const loading = ref(false) // 控制 loading
const ruleCode = ref(3) // 1：不正确 2：重复 3：zhe
const { tableRef, tableHeight } = calcTableHeight()

// 追溯码搜索
const formInline = reactive({
  traceableCode: '',
  hospital: '',
  createTime: '',
  createTimeBegin: '',
  createTimeEnd: '',
  count: 1,
  page: 1,
  pageSizes: 10,
  traceableData: [],
  detailDataDialog: []
})

// 追溯码保存
const saveFormCode = reactive({
  hospital: '',
  purchaseAddress: '',
  invoiceNumber: '', //  出库单号
  purchasesItemList: [],
  saveCode: '' //  保存的追溯码
})

// 时间选择器
const onTimeChange = (val) => {
  formInline.createTimeBegin = val[0]
  formInline.createTimeEnd = val[1]
}

// 重置按钮
const onRestBtn = async () => {
  formInline.traceableCode = ''
  formInline.hospital = ''
  formInline.createTime = ''
  formInline.createTimeBegin = ''
  formInline.createTimeEnd = ''
  await startDataFun()
}
// 搜索追溯码
const onSearchCode = async () => {
  await startDataFun()
}

const onExportError = (val) => {
  api.download(`/retrospect/purchases/export?traceableCode=${formInline.traceableCode}&hospital=${formInline.hospital}&page=${formInline.page}&limit=${formInline.pageSizes}&createTimeBegin=${formInline.createTimeBegin}&createTimeEnd=${formInline.createTimeEnd}`)
}
// 保存按钮
const onSaveCode = async () => {
  if (saveFormCode.hospital === '') {
    ElMessage.error('采购商不能为空')
    return
  }
  if (saveFormCode.purchasesItemList.length <= 0) {
    ElMessage.error('追溯码不能为空')
    return
  }
  const saveData = {
    hospital: saveFormCode.hospital,
    purchaseAddress: saveFormCode.purchaseAddress,
    invoiceNumber: saveFormCode.invoiceNumber,
    purchasesItemList: saveFormCode.purchasesItemList
  }
  const data = await api.post(`/retrospect/purchases/save`, saveData)
  if (data.code === 200) {
    ElMessage.success('保存成功')
  } else {
    ElMessage.error(data.message)
  }
  await startDataFun()
  dialogFormVisible.value = false
}

// 新建出库
const onOutbound = () => {
  restDialogFormVisible()
  dialogFormVisible.value = true
}

let timerId = null
const stopWatch = watch(() => saveFormCode.saveCode, (newValue, oldValue) => {
  if (timerId) {
    clearTimeout(timerId)
    timerId = null
  }
  timerId = setTimeout(() => {
    if (newValue.length === 0) {
      return
    }
    saveFormCode.purchasesItemList.unshift({
      traceableCode: newValue
    })
    ruleCode.value = 3
    saveFormCode.saveCode = ''
  }, 200)
}, {
  deep: true
})

// 删除追溯码
const onHandleClose = (tag) => {
  saveFormCode.purchasesItemList = saveFormCode.purchasesItemList.filter(item => item.traceableCode !== tag.traceableCode)
}
const onDeleteCode = async (row) => {
  ElMessageBox.confirm(
    `确定删除 ${row.hospital} 的出库单吗？`,
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      center: true
    }
  )
    .then(async () => {
      const data = await api.post(`/retrospect/purchases/del?purchasesId=${row.purchasesId}`)
      if (data.code !== 200) {
        ElMessage.error(data.message)
        return
      }
      ElMessage.success('删除成功')
      await startDataFun()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

// 初始化数据
const startDataFun = async () => {
  loading.value = true
  const params = {
    traceableCode: formInline.traceableCode,
    hospital: formInline.hospital,
    createTimeBegin: formInline.createTimeBegin,
    createTimeEnd: formInline.createTimeEnd
  }
  const { data } = await api.post(`/retrospect/purchases/list?page=${formInline.page}&limit=${formInline.pageSizes}`, params)
  formInline.traceableData = data.list
  formInline.count = data.count
  loading.value = false
}

// 重置dialogFormVisible
const restDialogFormVisible = () => {
  saveFormCode.hospital = ''
  saveFormCode.purchaseAddress = ''
  saveFormCode.invoiceNumber = ''
  saveFormCode.purchasesItemList = []
  saveFormCode.saveCode = ''
  ruleCode.value = 3
}

// 每页条数变化出发
const handleSizeChange = async (val) => {
  formInline.pageSizes = val
  await startDataFun()

}
// 当前页变化出发
const handleCurrentChange = async (val) => {
  formInline.page = val
  await startDataFun()
}

const formatDateTable = (timestamp) => {
  timestamp = timestamp / 1000
  const date = new Date(timestamp * 1000)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  const second = String(date.getSeconds()).padStart(2, '0')
  // 返回格式化的日期和时间字符串
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`
}

onMounted(async () => {
  await startDataFun()
})
</script>

<style lang="less" scoped>

.tableContainer {
  width: 100%;
  height: 100%;
  margin-top: 10px;

  .cardTop {
    margin-bottom: 5px;

    .traceableCodeInput {
      :deep(.el-input__wrapper) {
        width: 460px;
      }
    }

    .searchCondition {
      font-size: 16px;
      color: #303133;
      letter-spacing: 0;
      line-height: 16px;
      font-weight: 500;
    }

  }
}

.cardFoot {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: right;
}

.tooltipStyle {
  height: 530px;
  padding: 5px;

  .tooltipTitle {
    font-size: 16px;
    color: #303133;
    letter-spacing: 0;
    line-height: 16px;
    font-weight: 500;
  }

  .tooltipContent {
    margin-top: 8px;
    width: 430px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #303133;
    font-size: 15px;
    //-webkit-line-clamp: 2;
    //-webkit-box-orient: vertical;
    //overflow: hidden;
    //text-overflow: ellipsis;
  }
}

.tagCodeStyle {
  display: flex;
  align-items: center;

  .purchasesTag {
    margin-right: 5px;
    max-width: 430px;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.tagStyle {
  width: 100%;
  max-height: 100px;
  border: 1px solid #ccc;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  align-items: center;
}
</style>

